package com.cms.server.controller;

import com.cms.server.Entity.LoginEntity;
import com.cms.server.Entity.UserIDEntity;
import com.cms.server.mapper.RoleMapper;
import com.cms.server.mapper.UserMapper;
import com.cms.server.model.Role;
import com.cms.server.model.User;
import com.cms.server.tool.Global;
import com.cms.server.tool.sendMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;


    @PostMapping("/adduser")
    public String addUser(@RequestBody User user){
        int insert = userMapper.insert(user);
        return String.valueOf(insert);
    }

    @GetMapping("/adduser_get")
    public String addUser_get(@RequestParam(value = "id", required = false) Integer id,
                              @RequestParam(value = "username", required = false) String username,
                              @RequestParam(value = "password", required = false) String password,
                              @RequestParam(value = "del", required = false, defaultValue = "0") String del) {
        User user = new User();
        user.setUserid(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setStatus(1);
        int insert = userMapper.insert(user);
        return String.valueOf(insert);
    }

    @PostMapping("/updateuser")
    public String updateUser(@RequestBody User user){
        if(user.getUserid()==null){
            return "id not exit";
        }

        int updated = userMapper.updateById(user);
        return String.valueOf(updated);
    }
    @GetMapping("/deleteuser")
    public ResponseEntity<Map<String,String>> deleteUser(@RequestParam(value = "id", required = false) Integer id){
        if(id == null){
            id = Global.user_id;
        }
        User user = userMapper.selectById(id);
        user.setStatus(1);
        return ResponseEntity.ok(sendMessage.createResponse(true,"删除成功"));
    }

    @GetMapping("/getuser")
    public User getUser(@RequestParam Integer id){
        return userMapper.selectById(id);
    }

    @PostMapping("/passwordChange")
    public ResponseEntity<? extends Object> changePassword(@RequestParam Integer id,
                               @RequestParam String old,
                               @RequestParam String new_password){
        User user = userMapper.selectByIdAndPassword(id,old);
        if (user == null) {
            // 用户不存在或旧密码不正确
            return ResponseEntity.ok(sendMessage.createResponse(false,""));
        } else {
            // 更新用户密码
            user.setPassword(new_password);
            return ResponseEntity.ok(sendMessage.createResponse(true,""));
        }

    }

    @PostMapping("/register")
    public ResponseEntity<Map<String,String>> register(@RequestParam(value = "username", required = false) String username,
                                           @RequestParam(value = "password", required = false) String password,
                                           @RequestParam(value = "password_again", required = false) String password_again,
                                           @RequestParam(value = "del", required = false, defaultValue = "0") String del) {
        // 验证用户名和密码是否为空
        if (username == null || username.isEmpty() || password == null || password.isEmpty() || password_again == null || password_again.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(sendMessage.createResponse(false, "用户名和密码不能为空"));
        }

        // 验证用户名格式
        String usernamePattern = "^[\\w\\u4e00-\\u9fa5]{4,20}$";
        if (!Pattern.matches(usernamePattern, username)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(sendMessage.createResponse(false, "用户名应由4到20个汉字、字母、数字或下划线组成"));
        }

        // 验证密码格式
        if (password.length() < 6 || password.length() > 12) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(sendMessage.createResponse(false, "密码应由6到12个字符组成"));
        }

        // 验证密码和确认密码是否一致
        if (!password.equals(password_again)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(sendMessage.createResponse(false, "密码和确认密码不一致"));
        }

        // 检查用户名是否已存在
        Optional<User> existingUser = userMapper.selectByName(username);
        if (existingUser.isPresent()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(sendMessage.createResponse(false, "用户名已存在"));
        }

        // 创建新用户对象
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 应该在服务端加密密码
        newUser.setStatus(1);

        // 保存新用户
        int insert = userMapper.insert(newUser);
        if (insert > 0) {
            return ResponseEntity.ok(sendMessage.createResponse(true, "注册成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(sendMessage.createResponse(false, "注册失败"));
        }
    }

    @RequestMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody LoginEntity loginEntity) {
        // 验证用户名和密码是否为空
        if (loginEntity.getName() == null || loginEntity.getName().isEmpty() || loginEntity.getPassword() == null || loginEntity.getPassword().isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(sendMessage.createResponse(false, "用户名和密码不能为空"));
        }

        // 检查用户是否存在
        Optional<User> user = userMapper.selectByName(loginEntity.getName());
        if (!user.isPresent()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(sendMessage.createResponse(false, "用户名不存在"));
        }

        // 验证密码是否正确
        // 注意：这里应该使用加密后的密码进行比较
        if (!user.get().getPassword().equals(loginEntity.getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(sendMessage.createResponse(false, "密码错误"));
        }

        // 登录成功
        Global.user_id = user.get().getUserid();
        Map<String, Object>  response = sendMessage.createResponse(true, "登录成功");
        response.put("token", user.get().getUsername());  // 生成token
        Map<String,Object> send = new HashMap<>();
        response.put("id",user.get().getUserid());
        send.put("data",response);
        return ResponseEntity.ok(send);
    }

    // 返回用户信息和权限
    @PostMapping("/info")
    public ResponseEntity<Map<String,Object>> info(@RequestBody UserIDEntity userid){
        // 获取当前用户ID
        Integer user_id = userid.getUser_id();
        Map<String, Object> response = new HashMap<>();
        User user= userMapper.selectById(user_id);
        Role role = roleMapper.selectByUserId(user_id);
        response.put("user", user);
        response.put("role",role);
        Map<String, Object> send = new HashMap<>();
        send.put("status",true);
        send.put("data",response);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/getusernames")
    public  ResponseEntity<Map<String,Object>> getName(){
        List<User> users = userMapper.selectAllName();
        List<Map<String ,Object>> data = new ArrayList<>();

        for(User user : users){
            Map<String,Object> userInfo = new HashMap<>();
            userInfo.put("id",user.getUserid());
            userInfo.put("name",user.getUsername());
            data.add(userInfo);
        }

        Map<String,Object> res = new HashMap<>();
        res.put("status",true);
        res.put("data",data);

        return ResponseEntity.ok(res);
    }

}
